<?php
require __DIR__ . '/../vendor/autoload.php';

use ChatX\Mqtt\MqttPHP;

try {
    $topic = 'test/topic';
    $message = json_encode(['type'=>'demo','text' => 'hello']);
    $client_id = 'php-publisher-' . uniqid();
    $mqtt = new MqttPHP('127.0.0.1', '1883', $client_id);
    $mqtt->connect(true, null, null, null);
    echo "Connected to MQTT broker\n";
    $success = $mqtt->publish($topic, $message, 0);
    if ($success) {
        echo "Message published to $topic: $message\n";
    } else {
        echo "Failed to publish message\n";
    }
    $mqtt->close();
    echo "Disconnected from MQTT broker\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}